# -*- conding:UTF-8 -*-

'''
@ Project: funny
@ File: video.py
@ Author: 韩成瑾
@ Date：2022/10/24 20:16
解码url:https://tool.chinaz.com/tools/urlencode.aspx
请求url:https://www.douyin.com/video/7142103683742879016

'''
import json
from pprint import pprint

import requests
import re

"""
1.发送请求,模拟浏览器对于url地址发送请求
    requests: 模块  response:自定义变量响应对象
    
    得不到数据：
        被反爬  不是需要的数据--》headers cookie
"""

# 确定url
url = 'https://www.douyin.com/video/7142103683742879016'
headers = {
    "cookie":"ttwid=1%7CfOflbvefkorjf9J7r9TN-FmIeFW11BARSUOLM8xKbKI%7C1666696279%7C20260c52a8466ad8d6bd594df3b09950b8400f152afedb3ed7da2e32a79ea077; strategyABtestKey=1666696279.677; s_v_web_id=verify_l9o3xke8_uxZXCpYL_s5nq_48sA_8Ze4_esk7OQLb2F1O; passport_csrf_token=0af9a60f59c4ce341eff08a1f2dcf0db; passport_csrf_token_default=0af9a60f59c4ce341eff08a1f2dcf0db; ttcid=f2a9d97ead014af59ab6fc2fb499d1d318; tt_scid=-GFyZax3WIvPUq761Q1S3RE5NXeAHsPqUbwAYd5tCzkb9zta4fxCUh3K.kXrbL3x608c; download_guide=%221%2F20221025%22; home_can_add_dy_2_desktop=%221%22; msToken=bkCLfPCQfIeAwY34Rh3lB5rDs6NhWAYf-CeU0I6a7_J2MPtiL8S3lF4OdRTS38Dq1caztSi1XNouo2zZTBVARaYI8uio8lNFW3RUHiGkU-lMMBxyzdR107a4xJdXQQ==; msToken=FwnHBVMoGTmiIifuoLhm_lR9Cps_rJ0JOrxud_F8J2iwCOPs3uDqiFJ4OuTigMXueaiycGXQGITM2Z2r7wxCaLzGhNt4QMG_0SaK3J3CNccem8nBjQLg2ojWQKKhXQ==; __ac_nonce=06357d1f4002f8961fd77; __ac_signature=_02B4Z6wo00f01cdA4CwAAIDAGpXHVnRz.TXHYOSAABKJarPOmafusOWZF6zlr9pMOwgHXiDcIqLVLbliK54fRa-wGMb6CnnkcnPypej3G0TsGzMLWj33BELJDJCf7PbThTwH7diAsg2RfSYrae; __ac_referer=https://www.douyin.com/video/7142103683742879016",
    "user-agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.52'
}

response = requests.get(url=url,headers=headers)
text = response.text
# print(text)

# 提取标题
title = re.findall('<title data-react-helmet="true">(.*?)</title>',text)[0]
# print(title)

# 提取视频信息
html_video = re.findall('script id="RENDER_DATA" type="application/json">(.*?)</script',text)[0]
# print(html_video)


# 解码
video_info = requests.utils.unquote(html_video)
# print(video_info)

# 转化数据类型
json_video = json.loads(video_info)
# print(json_video)
# pprint(json_video)
json_video_info_url = 'https:' + json_video['33']['aweme']['detail']['video']['bitRateList'][0]['playAddr'][0]['src']
print(json_video_info_url)

# 保存数据

video_content = requests.get(url=json_video_info_url,headers=headers).content
with open('video_url\\' + title + '.mp4',mode='wb')as f:
    f.write(video_content)


# 一小时三十分钟